<template>
	<view class="form-container">
		<view class="form-item">
			<text class="label">照片：</text>
			<view class="content_upload">
				<view class="u-list-item" hover-stay-time="150" style="width: 200rpx;height: 200rpx;" @click="uploadImg">
					<template class="" v-if="!contentAvatarUrl">
						<uni-icons type="plusempty" size="40"></uni-icons>
						<view class="u-add-tips">选择图片</view>
					</template>
					<view class="photo" v-else>
						<image :src="contentAvatarUrl"></image>
					</view>
					<!-- <image class="u-avatar" v-else :src="contentAvatarUrl"></image> -->
				</view>
			</view>
		</view>
		<view class=" form-item">
			<text class="label">姓名：</text>
			<input type="text" v-model="employee.name" placeholder="请输入姓名" />
		</view>
		<view class="form-item">
			<text class="label">性别：</text>
			<radio-group @change="radioChange">
				<label>
					<radio value="M" :checked="isGender == 'M' ? true : false" /> 男
				</label>
				<label>
					<radio value="F" :checked="isGender == 'F' ? true : false" /> 女
				</label>
			</radio-group>
		</view>
		<view class="form-item">
			<text class="label">身份证号：</text>
			<input type="text" v-model="employee.idNumber" maxlength="18" placeholder="请输入身份证号码" />
		</view>
		<view class="form-item">
			<text class="label">出生日期：</text>
			<view class="uni-list">
				<view class="uni-list-cell">
					<view class="uni-list-cell-db">
						<picker mode="date" :value="birthDate" :start="startDate" :end="endDate"
							@change="bindbirthDateChange">
							<view class="uni-input">{{birthDate}}</view>
						</picker>
					</view>
				</view>
			</view>
		</view>
		<view class="form-item">
			<text class="label">工资：</text>
			<input type="number" v-model="employee.salary" placeholder="请输入工资" />
		</view>
		<view class="form-item">
			<text class="label">加入时间：</text>
			<view class="uni-list">
				<view class="uni-list-cell">
					<view class="uni-list-cell-db">
						<picker mode="date" :value="joinDate" :start="startDate" :end="endDate" @change="bindJoinDateChange">
							<view class="uni-input">{{joinDate}}</view>
						</picker>
					</view>
				</view>
			</view>
			<!-- <input type="date" v-model="employee.joinDate" /> -->
		</view>
		<view class="form-item">
			<text class="label">简历附件：</text>
			<view @click="uploadFile">{{fileName ? fileName : '点击上传附件'}}</view>
		</view>
		<view class="form-action">
			<button @click="submitAddForm" v-if="!updateInfo">添加</button>
			<button @click="submitUpdateForm" v-else>修改</button>
		</view>
	</view>
</template>

<script>
	import {
		addEmployeeInfo,
		getEmployeeList,
		getEmployeeById,
		updateEmployeeInfo
	} from '@/api/user.js'
	export default {
		data() {
			const currentDate = this.getDate({
				format: true
			})
			return {
				updateInfo: false,
				contentAvatarUrl: '',
				isGender: null,
				joinDate: '请选择日期',
				birthDate: '请选择日期',
				fileName: '',
				employee: {
					name: '',
					idNumber: '',
					gender: '',
					birthDate: '',
					photo: '',
					salary: '',
					joinDate: '',
					resume: ''
				},
				userId: null
			};
		},
		computed: {
			startDate() {
				return this.getDate('start');
			},
			endDate() {
				return this.getDate('end');
			}
		},
		onLoad(opt) {
			console.log(opt);
			if (opt.flag === 'true') {
				this.updateInfo = true
				this.userId = opt.id
				this.getEmployeeUserById(JSON.parse(opt.id))
			}
		},
		methods: {
			async getEmployeeUserById(id) {
				// 调用 getEmployeeById 函数并传递 id 参数
				const res = await getEmployeeById(id);
				// 检查响应代码是否为200，表示成功
				if (res.code === 200) {
					// 处理获取到的员工信息，例如将其保存到数据属性中
					this.employee = {
						// ...this.employee,
						name: res.data.name ? res.data.name : res.data.name,
						idNumber: res.data.id_number,
						gender: res.data.gender,
						birthDate: this.formatDate(res.data.birth_date),
						photo: res.data.photo,
						salary: res.data.salary,
						joinDate: this.formatDate(res.data.join_date),
						resume: res.data.resume
					};
					this.isGender = res.data.gender
					this.contentAvatarUrl = res.data.photo
					this.joinDate = this.formatDate(res.data.join_date)
					this.birthDate = this.formatDate(res.data.birth_date)
					this.employee.gender = res.data.gender == 'M' ? 'M' : 'F'
					console.log('获取员工信息成功', res);
				} else {
					// 处理错误情况，例如员工不存在或服务器错误
					console.error('获取员工信息失败', res);
					// 可以根据实际情况弹出提示或进行其他错误处理
				}
			},

			radioChange(e) {
				this.employee.gender = e.detail.value
			},
			uploadFile() {
				wx.chooseMessageFile({
					count: 1, // 默认9，设置文件选择数量
					type: 'file', // 选择文件
					success: (res) => {
						if (res.tempFiles.length > 0) {
							const file = res.tempFiles[0];
							this.fileName = file.name;
							this.employee.resume = file.path;
							console.log(res);
						}
					},
					fail: (err) => {
						console.error('选择文件失败:', err);
					}
				});
			},
			bindJoinDateChange(e) {
				this.joinDate = e.detail.value
				this.employee.joinDate = e.detail.value
			},
			bindbirthDateChange(e) {
				this.birthDate = e.detail.value
				this.employee.birthDate = e.detail.value
			},
			getDate(type) {
				const date = new Date();
				let year = date.getFullYear();
				let month = date.getMonth() + 1;
				let day = date.getDate();

				if (type === 'start') {
					year = year - 60;
				} else if (type === 'end') {
					year = year + 2;
				}
				month = month > 9 ? month : '0' + month;
				day = day > 9 ? day : '0' + day;
				return `${year}-${month}-${day}`;
			},
			uploadImg() {
				uni.chooseImage({
					count: 1,
					success: async res => {
						if (res.tempFilePaths.length > 0) {
							this.contentAvatarUrl = res.tempFilePaths[0]
							this.employee.photo = res.tempFilePaths[0]
						}
					}
				});
			},
			async submitUpdateForm() {
				console.log('修改');
				if (!this.isValidForm()) return;
				console.log(this.employee);
				const res = await updateEmployeeInfo(this.userId, this.employee)
				if (res.code === 200) {
					uni.showToast({
						title: '修改成功',
						icon: 'success'
					});
					setTimeout(() => {
						uni.redirectTo({
							url: '/pages/index/index'
						});
						uni.hideLoading();
					}, 1000);
				} else {
					uni.showToast({
						title: '修改失败',
						icon: 'none'
					});
				}

			},
			async submitAddForm() {
				console.log(this.employee);
				console.log('添加');
				if (!this.isValidForm()) return;
				// 在这里添加提交表单的逻辑
				const res = await addEmployeeInfo(this.employee)
				console.log('提交表单', this.employee);
				if (res.code === 200) {
					uni.hideLoading();
					uni.showToast({
						title: '添加成功',
						icon: 'success'
					});
					setTimeout(() => {
						uni.redirectTo({
							url: '/pages/index/index'
						});
					}, 2000);
				} else {
					uni.showToast({
						title: '添加失败',
						icon: 'none'
					});
				}
			},

			isValidForm() {
				const {
					name,
					idNumber,
					gender,
					birthDate,
					salary,
					joinDate,
					resume,
					photo
				} = this.employee;
				// 照片不能为空
				if (!photo) {
					uni.showToast({
						title: '照片不能为空',
						icon: 'none'
					});
					return false;
				}
				// 姓名不能为空
				if (!name) {
					uni.showToast({
						title: '姓名不能为空',
						icon: 'none'
					});
					return false;
				}

				// 身份证号码校验（18位，最后一位可能是X）
				if (!idNumber || idNumber.length !== 18 || !/^[\dXx]*$/.test(idNumber)) {
					uni.showToast({
						title: '身份证号码格式不正确',
						icon: 'none'
					});
					return false;
				}

				// 性别不能为空
				if (!gender) {
					uni.showToast({
						title: '性别不能为空',
						icon: 'none'
					});
					return false;
				}

				// 出生日期不能为空
				if (!birthDate) {
					uni.showToast({
						title: '出生日期不能为空',
						icon: 'none'
					});
					return false;
				}

				// 工资只能填写数字
				if (!salary || isNaN(salary) || salary === '') {
					uni.showToast({
						title: '工资不能为空且只能填写数字',
						icon: 'none'
					});
					return false;
				}

				// 加入时间不能为空
				if (!joinDate) {
					uni.showToast({
						title: '加入时间不能为空',
						icon: 'none'
					});
					return false;
				}

				// 简历附件不能为空
				if (!resume) {
					uni.showToast({
						title: '简历附件不能为空',
						icon: 'none'
					});
					return false;
				}

				// 如果所有校验通过
				return true;
			},

			formatDate(dateStr) {
				const date = new Date(dateStr);
				const year = date.getFullYear();
				const month = ('0' + (date.getMonth() + 1)).slice(-2);
				const day = ('0' + date.getDate()).slice(-2);
				// 返回格式化后的日期字符串
				return `${year}-${month}-${day}`;
			},
		}
	};
</script>

<style lang="scss">
	.form-container {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 30rpx;
	}

	.form-item {
		display: flex;
		align-items: center;
		margin-bottom: 30rpx;
		width: 100%;
	}

	.label {
		width: 180rpx; // 可以根据实际情况调整标签宽度
		font-size: 16px;
	}

	.content_upload {

		.u-list-item {
			width: 200rpx; // 一寸照宽度大约为200rpx
			height: 280rpx; // 一寸照高度大约为280rpx
			overflow: hidden;
			margin: 10rpx;
			background: rgb(244, 245, 246);
			position: relative;
			border-radius: 10rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			flex-direction: column;
			font-size: 26rpx;

			.u-add-tips {
				margin-top: 20rpx;
				line-height: 40rpx;
			}
		}

		.info {
			display: flex;
			width: 100%;
		}

		.photo {
			flex: 0 0 200rpx; // 一寸照的宽度大约为200rpx
			margin-right: 20rpx;
		}

		.photo image {
			width: 200rpx; // 设置图片宽度
			height: 280rpx; // 设置图片高度，一寸照的比例大约为1:1.4
			object-fit: cover; // 确保图片内容适应尺寸
			border-radius: 4rpx; // 圆角边框
		}

		.img {
			flex: 0 0 200rpx; // 一寸照的宽度大约为200rpx
			margin-right: 20rpx;

			image {
				width: 200rpx; // 设置图片宽度
				height: 280rpx; // 设置图片高度
				object-fit: cover; // 确保图片内容适应尺寸
				border-radius: 4rpx; // 圆角边框
			}
		}

	}

	input[type="text"],
	input[type="number"],
	input[type="date"],
	radio-group,
	upload {
		flex-grow: 1;
	}

	input[type="text"],
	input[type="number"],
	input[type="date"] {
		padding: 10rpx;
		font-size: 16px;
		border: 1rpx solid #eaeaea;
		border-radius: 4rpx;
	}

	radio-group {
		display: flex;
	}

	radio {
		margin-right: 10rpx;
	}

	upload {
		display: block;
		margin-top: 10rpx;
	}

	.form-action {
		display: flex;
		justify-content: center;
		margin-top: 50rpx;
	}

	button {
		padding: 15rpx 40rpx;
		font-size: 18px;
		color: #fff;
		background-color: #007aff;
		border: none;
		border-radius: 8rpx;
		box-shadow: 0 4rpx 8rpx rgba(0, 122, 255, 0.2); // 添加立体感的阴影
		transition: all 0.3s ease; // 平滑过渡效果
	}

	button:active {
		background-color: #0056b3;
		box-shadow: 0 2rpx 4rpx rgba(0, 122, 255, 0.2);
		transform: translateY(2rpx); // 点击时按钮下移，增强立体感
	}
</style>